package com.app.newiptv.activity;

import android.animation.Animator;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.app.newiptv.R;
import com.app.newiptv.bean.ChannelType;
import com.app.newiptv.bean.HomeRecommondInfoBean;
import com.app.newiptv.bean.UserLogin;
import com.app.newiptv.bean.Version;
import com.app.newiptv.bean.VodItemBean;
import com.app.newiptv.utils.Paths;
import com.app.newiptv.view.MetroItemFrameLayout;
import com.app.newiptv.view.MetroViewBorderHandler;
import com.app.newiptv.view.MetroViewBorderImpl;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.dueeeke.videoplayer.exo.ExoMediaPlayerFactory;
import com.dueeeke.videoplayer.player.PlayerFactory;
import com.dueeeke.videoplayer.player.VideoViewConfig;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

import static com.app.newiptv.activity.Contast.TAG;
import static com.app.newiptv.utils.Paths.BASEPATH;
import static com.app.newiptv.utils.Paths.BASE_SUFFIX;
import static com.app.newiptv.utils.Paths.HOSTPATH;
import static com.app.newiptv.utils.Paths.URL_SERVER;

// implements SetFocusCallBack
public class SplashHomeActivity extends Activity implements View.OnClickListener {
    private TextView timeText;
    private TextView dayText;
    private TextView weekText;

    private ImageView movie1ImageView;
    private ImageView movie2ImageView;
    private ImageView movie3ImageView;
    private TextView movie1TextView;
    private TextView movie2TextView;
    private TextView movie3TextView;

//    private ImageView sitcomImageView;
//    private TextView sitcomTextView;

    private ImageView varietyImageView;
    private TextView varietyTextView;

    private ImageView cartoonImageView;
    private TextView cartoonTextView;

    private MetroItemFrameLayout nightBlock; // view12
    private MetroItemFrameLayout cartoonBlock; // view13
    private MetroItemFrameLayout vipBlueBlock; // view7
    private MetroItemFrameLayout varietyBlock; // view8
    private MetroItemFrameLayout movieBlock; // view10
    private MetroItemFrameLayout sitcomBlock; // view11

    private MetroItemFrameLayout movieShow1Block; // view
    private MetroItemFrameLayout movieShow2Block; // view4
    private MetroItemFrameLayout movieShow3Block; // view2
    private MetroItemFrameLayout varietyShowBlock; // view3
    private MetroItemFrameLayout sitcomShowBlock; // view5
    private MetroItemFrameLayout cartoonShowBlock; // view6

    private LinearLayout searchLinearLayout;
    private LinearLayout loginLinearLayout;
    private LinearLayout recodeLinearLayout;
    private LinearLayout collectLinearLayout;
    private TextView user;
    private SharedPreferences preferences;
    private String user_save;
    private String password_save;
    private String isLogin;
    File apkFile;
    private Intent loginIntent;
    private ChannelType channelTypeInfo;
    private VodItemBean moviewItemBean;
    private Intent startVodIntent;
    private SimpleDateFormat sdf;
    private Date date;
    private List<HomeRecommondInfoBean> recommondInfoBeans = new ArrayList<>();
    private final static int UPDATE_TIME = 999;
    private final static int DOWNLOAD_COMPLETE = 1000;
    private Map<String, String> httpHeaders;
    private Handler timeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_TIME:
                    setDataAndTimeInfo();
                    break;
                case DOWNLOAD_COMPLETE:
                    if (apkFile != null && apkFile.exists()) {
//                        installSilently(apkFile.getAbsolutePath());
                        installApp();
                    }
                    break;
            }
        }
    };
    private List<Integer> movies = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_layout);
        Contast.globalContext = this;
        initView();
        try {
            VideoViewConfig config = VideoViewManager.getConfig();
            Field mPlayerFactoryField = config.getClass().getDeclaredField("mPlayerFactory");
            mPlayerFactoryField.setAccessible(true);
            PlayerFactory playerFactory = ExoMediaPlayerFactory.create();
            mPlayerFactoryField.set(config, playerFactory);
            Log.i(TAG, "initView: 设置成exo播放器");
        } catch (Exception e) {
            Log.i(TAG, "initView: exception");
        }
        sdf = new SimpleDateFormat("MM-dd HH:mm E");
        date = new Date(System.currentTimeMillis());
        loginIntent = new Intent(this, LoginActivity.class);
        loginIntent.putExtra("data", "i come from MainAcvitity");
        startVodIntent = new Intent(SplashHomeActivity.this, VodActivity.class);
        if (!isNetworkOnline(BASEPATH)) {
            OkHttpUtils.get().url(URL_SERVER).build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(String response, int id) {
                    Log.i("legend!!!", response);
                    String[] urls = response.split("====");
                    boolean flag = false;
                    for (int i = 0; i < urls.length; i++) {
                        if (isNetworkOnline(urls[i])) {
                            BASEPATH = urls[i];
                            HOSTPATH = BASEPATH + BASE_SUFFIX;
                            flag = true;
                            preferences = getApplicationContext().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
                            Log.i("legend!!!", HOSTPATH);
                            login();
                            break;
                        }
                    }
                    if (!flag) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        showNetWorkDialog();
                                    }
                                });
                            }
                        }).start();
                    }
                }
            });

        } else {
            preferences = getApplicationContext().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
            login();
        }


        FrameLayout roundedFrameLayout = new FrameLayout(this);
        roundedFrameLayout.setClipChildren(false);
        final MetroViewBorderImpl metroViewBorderImpl = new MetroViewBorderImpl(roundedFrameLayout);
        metroViewBorderImpl.setBackgroundResource(R.drawable.border_color);

        ViewGroup list = (ViewGroup) findViewById(R.id.list);
        metroViewBorderImpl.attachTo(list);

        metroViewBorderImpl.getViewBorder().addOnFocusChanged(new MetroViewBorderHandler.FocusListener() {
            @Override
            public void onFocusChanged(View oldFocus, final View newFocus) {
                metroViewBorderImpl.getView().setTag(newFocus);

            }
        });
        metroViewBorderImpl.getViewBorder().addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                View t = metroViewBorderImpl.getView().findViewWithTag("top");
                if (t != null) {
                    ((ViewGroup) t.getParent()).removeView(t);
                    View of = (View) metroViewBorderImpl.getView().getTag(metroViewBorderImpl.getView().getId());
                    ((ViewGroup) of).addView(t);
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                View nf = (View) metroViewBorderImpl.getView().getTag();
                if (nf != null) {
                    View top = nf.findViewWithTag("top");
                    if (top != null) {
                        ((ViewGroup) top.getParent()).removeView(top);
                        ((ViewGroup) metroViewBorderImpl.getView()).addView(top);
                        metroViewBorderImpl.getView().setTag(metroViewBorderImpl.getView().getId(), nf);

                    }
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

    }

    private void installApp() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(apkFile),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }

    //安装apk
    private String installSilently(String path) {
        // 通过命令行来安装APK
        String[] args = {"pm", "install", "-r", path};
        String result = "";
        // 创建一个操作系统进程并执行命令行操作
        ProcessBuilder processBuilder = new ProcessBuilder(args);
        Process process = null;
        InputStream errIs = null;
        InputStream inIs = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int read = -1;
            process = processBuilder.start();
            errIs = process.getErrorStream();
            while ((read = errIs.read()) != -1) {
                baos.write(read);
            }
            baos.write('\n');
            inIs = process.getInputStream();
            while ((read = inIs.read()) != -1) {
                baos.write(read);
            }
            byte[] data = baos.toByteArray();
            result = new String(data);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (errIs != null) {
                    errIs.close();
                }
                if (inIs != null) {
                    inIs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }

    private void initView() {
        nightBlock = (MetroItemFrameLayout) findViewById(R.id.view12);
        cartoonBlock = (MetroItemFrameLayout) findViewById(R.id.view13);
        vipBlueBlock = (MetroItemFrameLayout) findViewById(R.id.view7);
        varietyBlock = (MetroItemFrameLayout) findViewById(R.id.view8);
        movieBlock = (MetroItemFrameLayout) findViewById(R.id.view10);
        sitcomBlock = (MetroItemFrameLayout) findViewById(R.id.view11);
        movieShow1Block = (MetroItemFrameLayout) findViewById(R.id.view);
        movieShow2Block = (MetroItemFrameLayout) findViewById(R.id.view4);
        movieShow3Block = (MetroItemFrameLayout) findViewById(R.id.view2);
        varietyShowBlock = (MetroItemFrameLayout) findViewById(R.id.view3);
        sitcomShowBlock = (MetroItemFrameLayout) findViewById(R.id.view5);
        cartoonShowBlock = (MetroItemFrameLayout) findViewById(R.id.view6);

        timeText = (TextView) findViewById(R.id.activity_splash_time);
        dayText = (TextView) findViewById(R.id.activity_splash_day);
        weekText = (TextView) findViewById(R.id.activity_splash_week);
        movie1ImageView = (ImageView) findViewById(R.id.activity_splash_movie1_show);
        movie2ImageView = (ImageView) findViewById(R.id.activity_splash_movie2_show);
        movie3ImageView = (ImageView) findViewById(R.id.activity_splash_movie3_show);
        movie1TextView = (TextView) findViewById(R.id.activity_splash_movie1_text_show);
        movie2TextView = (TextView) findViewById(R.id.activity_splash_movie2_text_show);
        movie3TextView = (TextView) findViewById(R.id.activity_splash_movie3_text_show);
        varietyImageView = (ImageView) findViewById(R.id.activity_splash_variety_show);
        varietyTextView = (TextView) findViewById(R.id.activity_splash_variety_text_show);

        cartoonImageView = (ImageView) findViewById(R.id.activity_splash_cartoon_show);
        cartoonTextView = (TextView) findViewById(R.id.activity_splash_cartoon_text_show);

//        sitcomImageView = (ImageView) findViewById(R.id.activity_splash_sitcom_show);
//        sitcomTextView = (TextView) findViewById(R.id.activity_splash_sitcom_text_show);

        searchLinearLayout = (LinearLayout) findViewById(R.id.activity_splash_search);
        loginLinearLayout = (LinearLayout) findViewById(R.id.activity_splash_login);
        recodeLinearLayout = (LinearLayout) findViewById(R.id.activity_splash_recode);
        collectLinearLayout = (LinearLayout) findViewById(R.id.activity_splash_collect);
        user = (TextView) findViewById(R.id.activity_splash_user);

        nightBlock.setOnClickListener(this);
        cartoonBlock.setOnClickListener(this);
        vipBlueBlock.setOnClickListener(this);
        varietyBlock.setOnClickListener(this);
        movieBlock.setOnClickListener(this);
        sitcomBlock.setOnClickListener(this);
        movieShow1Block.setOnClickListener(this);
        movieShow2Block.setOnClickListener(this);
        movieShow3Block.setOnClickListener(this);
        varietyShowBlock.setOnClickListener(this);
        sitcomShowBlock.setOnClickListener(this);
        cartoonShowBlock.setOnClickListener(this);
        searchLinearLayout.setOnClickListener(this);
        loginLinearLayout.setOnClickListener(this);
        recodeLinearLayout.setOnClickListener(this);
        collectLinearLayout.setOnClickListener(this);
        searchLinearLayout.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    view.setBackgroundResource(R.drawable.linea_border);
                } else {
                    view.setBackgroundResource(0);
                }
            }
        });
        loginLinearLayout.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    view.setBackgroundResource(R.drawable.linea_border);
                } else {
                    view.setBackgroundResource(0);
                }
            }
        });
        recodeLinearLayout.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    view.setBackgroundResource(R.drawable.linea_border);
                } else {
                    view.setBackgroundResource(0);
                }
            }
        });
        collectLinearLayout.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    view.setBackgroundResource(R.drawable.linea_border);
                } else {
                    view.setBackgroundResource(0);
                }
            }
        });
    }

    public boolean isNetworkOnline(String address) {
        String host = "";
        if (address.indexOf("https://") != -1) {
            String noHeader = address.replace("https://", "");
            if (noHeader.indexOf("/") != -1) {
                String hostPort = noHeader.replace("/", "");
                if (hostPort.indexOf(":") != -1) {
                    host = hostPort.split(":")[0];
                } else {
                    host = hostPort;
                }
            }
        }
        if (address.indexOf("http://") != -1) {
            String noHeader = address.replace("http://", "");
            if (noHeader.indexOf("/") != -1) {
                String hostPort = noHeader.replace("/", "");
                if (hostPort.indexOf(":") != -1) {
                    host = hostPort.split(":")[0];
                } else {
                    host = hostPort;
                }
            }
        }
        Runtime runtime = Runtime.getRuntime();
        Log.i("legend!!!", "current host" + host);
        try {
            Process ipProcess = runtime.exec("ping -c 1 -w 100 " + host);
            int exitValue = ipProcess.waitFor();
            Log.i("Avalible", "Process:" + exitValue);
            if (exitValue == 0) {
                return true;
            } else {
                return false;
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    private void setDataAndTimeInfo() {
        date.setTime(System.currentTimeMillis());
        String currentDate = sdf.format(date);
        String[] dates = currentDate.split(" ");
        dayText.setText(dates[0]);
        timeText.setText(dates[1]);
        weekText.setText(dates[2]);
    }

    private void showNetWorkDialog() {
        new AlertDialog.Builder(this)
                .setTitle("警告")
                .setMessage("您的网络不可用,请检查!")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        timeHandler.sendEmptyMessage(UPDATE_TIME);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                        timeHandler.sendEmptyMessage(UPDATE_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();
    }

    public void enterVodDetail(int id) {
        if (TextUtils.isEmpty(Contast.USE_TOKEN) || TextUtils.isEmpty(Contast.USE_UID) || TextUtils.isEmpty(Contast.USE_GROUP)) {
            Toast.makeText(this, "请先登录或重新登录", Toast.LENGTH_LONG).show();
        } else {
            Intent vodIntent = new Intent(SplashHomeActivity.this, FilmDetailsActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("id", id);
            vodIntent.putExtra("bundle", bundle);
            startActivity(vodIntent);
        }
    }

    public void sitcomDetail(int id) {
        if (TextUtils.isEmpty(Contast.USE_TOKEN) || TextUtils.isEmpty(Contast.USE_UID) || TextUtils.isEmpty(Contast.USE_GROUP)) {
            Toast.makeText(this, "请先登录或重新登录", Toast.LENGTH_LONG).show();
        } else {
            Intent sitcomIntent = new Intent(SplashHomeActivity.this, SitcomActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("id", id);
            sitcomIntent.putExtra("bundle", bundle);
            startActivity(sitcomIntent);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_splash_recode:
                Intent recodeIntent = new Intent(SplashHomeActivity.this, RecodeAndCollectActivity.class);
                recodeIntent.putExtra("type", 0);
                startActivity(recodeIntent);
                break;
            case R.id.activity_splash_collect:
                Intent collectIntent = new Intent(SplashHomeActivity.this, RecodeAndCollectActivity.class);
                collectIntent.putExtra("type", 1);
                startActivity(collectIntent);
                break;
            case R.id.view:
                for (int i = 0; i < recommondInfoBeans.size(); i++) {
                    if (recommondInfoBeans.get(i).getView().getId() == R.id.view) {
                        enterVodDetail(Integer.valueOf(recommondInfoBeans.get(i).getVodBean().getVod_id()));
                    }
                }
                break;
            // movieShow3Block
            case R.id.view2:
                for (int i = 0; i < recommondInfoBeans.size(); i++) {
                    if (recommondInfoBeans.get(i).getView().getId() == R.id.view2) {
                        enterVodDetail(Integer.valueOf(recommondInfoBeans.get(i).getVodBean().getVod_id()));
                    }
                }
                break;
            // varietyShowBlock
            case R.id.view3:
                for (int i = 0; i < recommondInfoBeans.size(); i++) {
                    if (recommondInfoBeans.get(i).getView().getId() == R.id.view3) {
                        sitcomDetail(Integer.valueOf(recommondInfoBeans.get(i).getVodBean().getVod_id()));
                    }
                }
                break;
            // movieShow2Block
            case R.id.view4:
                for (int i = 0; i < recommondInfoBeans.size(); i++) {
                    if (recommondInfoBeans.get(i).getView().getId() == R.id.view4) {
                        enterVodDetail(Integer.valueOf(recommondInfoBeans.get(i).getVodBean().getVod_id()));
                    }
                }
                break;
            // sitcomShowBlock
            case R.id.view5:
//                for (int i = 0; i < recommondInfoBeans.size(); i++) {
//                    if (recommondInfoBeans.get(i).getView().getId() == R.id.view5) {
//                        sitcomDetail(Integer.valueOf(recommondInfoBeans.get(i).getVodBean().getVod_id()));
//                    }
//                }
                startToVodActivity(getType("电视直播"));
                break;
            // cartoonShowBlock
            case R.id.view6:
                for (int i = 0; i < recommondInfoBeans.size(); i++) {
                    if (recommondInfoBeans.get(i).getView().getId() == R.id.view6) {
                        sitcomDetail(Integer.valueOf(recommondInfoBeans.get(i).getVodBean().getVod_id()));
                    }
                }
                break;
            // vipBlueBlock
            case R.id.view7:
                startToVodActivity(getType("VIP蓝光影院"));
                break;
            // varietyBlock
            case R.id.view8:
//                if (TextUtils.isEmpty(Contast.USE_TOKEN) || TextUtils.isEmpty(Contast.USE_UID) || TextUtils.isEmpty(Contast.USE_GROUP)) {
//                    Toast.makeText(this, "请先登录或重新登录", Toast.LENGTH_LONG).show();
//                } else {
//                    startActivity(new Intent(this, AdultActivity.class));
//                }
                startToVodActivity(getType("午夜影院"));
                break;
            // movieBlock
            case R.id.view10:
                startToVodActivity(getType("电影"));
                break;
            // sitcomBlock
            case R.id.view11:
                startToVodActivity(getType("连续剧"));
                break;
            // nightBlock
            case R.id.view12:
                startToVodActivity(getType("综艺"));
                break;
            // cartoonBlock
            case R.id.view13:
                startToVodActivity(getType("动漫"));
                break;
            case R.id.activity_splash_search:
                Intent intent = new Intent(SplashHomeActivity.this, SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.activity_splash_login:
                startActivityForResult(loginIntent, 100);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1001 && requestCode == 100) {
            user.setText(data.getStringExtra("username"));
            getTypes();
            getRecommendInfo();
        }
//        if (requestCode == 123) {
//
//            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                // 检查该权限是否已经获取
//                for (int j =0;j<permissions.length; j++){
//                    int i = ContextCompat.checkSelfPermission(this, permissions[j]);
//                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
//                    if (i != PERMISSION_GRANTED) {
//                        // 提示用户应该去应用设置界面手动开启权限
//                        showDialogTipUserGoToAppSettting();
//                    } else {
//                        if (dialog != null && dialog.isShowing()) {
//                            dialog.dismiss();
//                        }
//                        Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
//                    }
//                }
//            }
//        }
    }

    private void startToVodActivity(String bigType) {
        if (TextUtils.isEmpty(Contast.USE_TOKEN) || TextUtils.isEmpty(Contast.USE_UID) || TextUtils.isEmpty(Contast.USE_GROUP)) {
            Toast.makeText(this, "请先登录或重新登录", Toast.LENGTH_LONG).show();
        } else {
            startVodIntent.putExtra("type_big_id", bigType);
            startActivity(startVodIntent);
        }
    }

    private void getRecommendInfo() {
        OkHttpUtils.post().addParams("uid", Contast.USE_UID).addParams("token", Contast.USE_TOKEN).url(HOSTPATH + Paths.CHANNLE_LIST + "?t=101").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    Log.i(TAG, "recommendResponse: " + response);
                    VodItemBean current = JSON.parseObject(response, VodItemBean.class);
                    final List<VodItemBean.VodItemInfo> list = current.getData().getList();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setRecommendPic(list.get(0).getVod_pic(), movie1ImageView);
                            setRecommendPic(list.get(1).getVod_pic(), movie2ImageView);
                            setRecommendPic(list.get(2).getVod_pic(), movie3ImageView);
                            setRecommendText(list.get(0).getVod_name(), movie1TextView);
                            setRecommendText(list.get(1).getVod_name(), movie2TextView);
                            setRecommendText(list.get(2).getVod_name(), movie3TextView);
                        }
                    });
                    recommondInfoBeans.add(new HomeRecommondInfoBean(list.get(0), movieShow1Block));
                    recommondInfoBeans.add(new HomeRecommondInfoBean(list.get(1), movieShow2Block));
                    recommondInfoBeans.add(new HomeRecommondInfoBean(list.get(2), movieShow3Block));
                } catch (Exception e) {
                }
            }
        });
//        OkHttpUtils.post().addParams("uid", Contast.USE_UID).addParams("token", Contast.USE_TOKEN).url(HOSTPATH + Paths.CHANNLE_LIST + "?t=202").build().execute(new StringCallback() {
//            @Override
//            public void onError(Call call, Exception e, int id) {
//
//            }
//
//            @Override
//            public void onResponse(String response, int id) {
//                try {
//                    Log.i(TAG, "onResponse: " + response);
//                    VodItemBean current = JSON.parseObject(response, VodItemBean.class);
//                    final List<VodItemBean.VodItemInfo> list = current.getData().getList();
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            setRecommendPic(list.get(0).getVod_pic(), sitcomImageView);
//                            setRecommendText(list.get(0).getVod_name(), sitcomTextView);
//                        }
//                    });
//                    recommondInfoBeans.add(new HomeRecommondInfoBean(list.get(0), sitcomShowBlock));
//                } catch (Exception e) {
//                }
//            }
//        });
        OkHttpUtils.post().addParams("uid", Contast.USE_UID).addParams("token", Contast.USE_TOKEN).url(HOSTPATH + Paths.CHANNLE_LIST + "?t=302").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    Log.i(TAG, "onResponse: " + response);
                    VodItemBean current = JSON.parseObject(response, VodItemBean.class);
                    final List<VodItemBean.VodItemInfo> list = current.getData().getList();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setRecommendPic(list.get(0).getVod_pic(), varietyImageView);
                            setRecommendText(list.get(0).getVod_name(), varietyTextView);
                        }
                    });
                    recommondInfoBeans.add(new HomeRecommondInfoBean(list.get(0), varietyShowBlock));
                } catch (Exception e) {
                }
            }
        });
        OkHttpUtils.post().addParams("uid", Contast.USE_UID).addParams("token", Contast.USE_TOKEN).url(HOSTPATH + Paths.CHANNLE_LIST + "?t=401").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    Log.i(TAG, "onResponse: " + response);
                    VodItemBean current = JSON.parseObject(response, VodItemBean.class);
                    final List<VodItemBean.VodItemInfo> list = current.getData().getList();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setRecommendPic(list.get(0).getVod_pic(), cartoonImageView);
                            setRecommendText(list.get(0).getVod_name(), cartoonTextView);
                        }
                    });
                    recommondInfoBeans.add(new HomeRecommondInfoBean(list.get(0), cartoonShowBlock));
                } catch (Exception e) {
                }
            }
        });
    }

    private void setRecommendPic(String url, ImageView imageView) {
        Glide.with(SplashHomeActivity.this)
                .load(BASEPATH + url)
                .priority(Priority.LOW)
                .placeholder(R.mipmap.iron)
                .error(R.mipmap.iron)
                .into(imageView);
    }

    private void setRecommendText(String text, TextView textView) {
        textView.setText(text.trim());
    }

    private String getType(String typeName) {
        if (channelTypeInfo != null) {
            List<ChannelType.DataBean> data = channelTypeInfo.getData();
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getT_name().equals(typeName)) {
                    return data.get(i).getT_id();
                }
            }
        } else {

        }
        return "1";
    }

    private void versions() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.post()
                        .addParams("uid", Contast.USE_UID)
                        .addParams("token", Contast.USE_TOKEN)
                        .url(HOSTPATH + Paths.VERSION)
                        .build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i(TAG, "versions:" + response);

//                        response = "{\"version\":\"1.0\",\"down_url\":\"http://192.168.0.106:8000/app-debug.apk\",\"is_online\":\"0\"}";
                        final Version version = JSON.parseObject(response, Version.class);
                        try {
                            String versionCodeName = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
                            int versionCode = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
                            Log.i(TAG, "version_name: " + versionCodeName);
                            Log.i(TAG, "version_code: " + versionCode);
                            if (version.getCode() == 1 && !TextUtils.isEmpty(version.getData().getVersion())) {
                                if (Float.parseFloat(versionCodeName) < Float.parseFloat(version.getData().getVersion())) {
                                    // 强制更新
                                    if (version.getData().getIs_online() == 1) {
                                        Toast.makeText(SplashHomeActivity.this, "正在后台下载", Toast.LENGTH_LONG).show();
                                        if (version.getData().getDown_url().contains("http")) {
                                            loadFile(version.getData().getDown_url(), getFilesDir().getAbsolutePath() + "/", "iptv_new.apk");
                                        } else {
                                            loadFile("http://" + version.getData().getDown_url(), getFilesDir().getAbsolutePath() + "/", "iptv_new.apk");
                                        }
                                    } else {
                                        // 用户选择更新
                                        AlertDialog.Builder builder = new AlertDialog.Builder(SplashHomeActivity.this);
                                        builder.setTitle("升级提醒");
                                        builder.setMessage("是否下载升级应用?");
                                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                                Toast.makeText(SplashHomeActivity.this, "正在后台下载", Toast.LENGTH_LONG).show();
                                                if (version.getData().getDown_url().contains("http")) {
                                                    loadFile(version.getData().getDown_url(), getFilesDir().getAbsolutePath() + "/", "iptv_new.apk");
                                                } else {
                                                    loadFile("http://" + version.getData().getDown_url(), getFilesDir().getAbsolutePath() + "/", "iptv_new.apk");
                                                }
                                            }
                                        });
                                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        });
                                        builder.show();
                                    }
                                }
                            }
                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();
    }

    public void loadFile(final String saveUrl, String path, String name) {
        File file = new File(path, name);
        if (file != null && file.exists()) {
            file.delete();
        }
        OkHttpUtils.get().url(saveUrl).build()
                .execute(new FileCallBack(path, name) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("legend", "onError: ");
                        Log.i("legend", "onError: " + e.toString());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        Log.i("legend", "onResponse: ");
                        if (saveUrl.contains("apk")) {
                            apkFile = response;
                            Log.i("legend", "onResponse: " + response.getPath());
                            Log.i("legend", "onResponse: " + response.getAbsolutePath());
                            try {
                                Runtime.getRuntime().exec("chmod 777 " + response.getAbsolutePath());
                                timeHandler.sendEmptyMessageDelayed(DOWNLOAD_COMPLETE, 2000);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }

    private void getTypes() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.post().addParams("uid", Contast.USE_UID).addParams("token", Contast.USE_TOKEN).url(HOSTPATH + Paths.CHANNEL_TYPES).build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
//                        Intent intent = new Intent(SplashHomeActivity.this, TestActivity.class);
//                        intent.putExtra("type", "onError");
//                        intent.putExtra("result", e.toString());
//                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            Log.i(TAG, "typeResponse: " + response);
//                            Intent intent = new Intent(SplashHomeActivity.this, TestActivity.class);
//                            intent.putExtra("type", "onResponse");
//                            intent.putExtra("result", response);
//                            startActivity(intent);
                            channelTypeInfo = JSON.parseObject(response, ChannelType.class);
                            Log.i(TAG, channelTypeInfo.toString());
                        } catch (Exception e) {
                        }

                    }
                });
            }
        }).start();
    }

    private void login() {
        user_save = preferences.getString("username", "");
        password_save = preferences.getString("password", "");
        isLogin = preferences.getString("sousuo", "");
        if (!(TextUtils.isEmpty(user_save) || TextUtils.isEmpty(password_save)) && isLogin.equals("1")) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        com.lzy.okhttputils.OkHttpUtils
                                .post(HOSTPATH + Paths.USER_LOGIN)
                                .params("u_name", user_save)
                                .params("u_password", password_save)
                                .connTimeOut(10000)
                                .execute(new com.lzy.okhttputils.callback.StringCallback() {
                                    @Override
                                    public void onError(Call call, Response response, Exception e) {
                                        super.onError(call, response, e);
                                        Contast.USE_TOKEN = "";
                                        Contast.USE_GROUP = "";
                                        Contast.USE_UID = "";
                                        startActivityForResult(loginIntent, 100);
                                    }

                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        Log.i(TAG, "loginReponse: " + s);
                                        try {
                                            final UserLogin loginInfo = JSON.parseObject(s, UserLogin.class);
                                            if (loginInfo.getCode() == 1) {
                                                Contast.USE_TOKEN = loginInfo.getData().getToken();
                                                Contast.USE_GROUP = loginInfo.getData().getU_group();
                                                Contast.USE_UID = loginInfo.getData().getU_id();
                                                httpHeaders = new HashMap<>();
                                                httpHeaders.put("Accept", "application/json");
                                                httpHeaders.put("Token", Contast.USE_TOKEN);
                                                httpHeaders.put("Uid", Contast.USE_UID);
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        user.setText(loginInfo.getData().getU_name());
                                                    }
                                                });
                                                getTypes();
                                                getRecommendInfo();
                                                versions();
                                            } else {
                                                startActivityForResult(loginIntent, 100);
                                            }
                                        } catch (Exception e) {

                                        }


                                    }
                                });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        } else {
            startActivityForResult(loginIntent, 100);
        }
    }
}
